package net.pimpas.web.jsf.renderers.command.ajax;

import java.io.IOException;

import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import net.pimpas.util.reflection.ReflectionUtil;
import net.pimpas.web.jsf.renderers.AjaxRendererBase;
import net.pimpas.web.jsf.renderers.RendererBase;
import net.pimpas.web.jsf.util.ComponentUtils;

import org.apache.myfaces.shared_impl.renderkit.JSFAttr;

public class AjaxCommandRenderer extends RendererBase implements AjaxRendererBase {
	
	public static final String JAVASCRIPT_HANDLER	= "pimpas.AJAX.Populate.Input";

	public String getJavascriptHandler() {
		return JAVASCRIPT_HANDLER;
	}
	
	@Override
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UICommand.class)) return;
		
		// get command button value
        Object value = this.getValue(component);
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement("value", component);
        writer.write((value!=null) ? String.valueOf(value) : "");
        writer.endElement("value");
		
	}
	
	private Object getValue( UIComponent cp ) {
		/**
		 * extracted from myfaces 1.1.5
		 */
		return (ReflectionUtil.isSubclass(cp.getClass(), ValueHolder.class)) ? 
				((ValueHolder)cp).getValue(): cp.getAttributes().get(JSFAttr.VALUE_ATTR);
	}
}
